import { isPhone, isEmail as _isEmail } from "@pureadmin/utils";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { reactive } from "vue";
import type { FormRules } from "element-plus";

/**
 * 获取表单验证规则
 * @param excludeId 排除的ID（修改表单时传入）
 */
export function getFormRules(excludeId?: number | string) {
  return reactive(<FormRules>{
    Name: [
      { required: true, message: "租户名称为必填项", trigger: "blur" },
      {
        validator: async (rule, value, callback) => {
          if (!value) {
            callback();
            return;
          }

          try {
            const params = {
              name: value
            };

            // 如果提供了excludeId，添加到参数中
            if (excludeId) {
              (
                params as { name: string; excludeId?: number | string }
              ).excludeId = excludeId;
            }
            console.log("params", params);
            const res = await http.get(
              changeHttpLink("/api/Tenant/check-name-unique"),
              { params }
            );
            console.log("调用检查", res);
            // 添加类型断言以解决TypeScript类型检查问题
            const typedRes = res as {
              Success: boolean;
              Data?: boolean;
            };
            if (typedRes.Success && typedRes.Data) {
              // 检查通过
              console.log("检查通过");
              callback();
            } else {
              callback(new Error("租户名称已存在"));
            }
          } catch (error) {
            console.error("唯一性检查失败", error);
            callback(new Error("租户名称唯一性检查失败，请稍后重试"));
          }
        },
        trigger: "blur"
      }
    ],
    Contact: [{ required: true, message: "联系人为必填项", trigger: "blur" }],
    Tel: [
      { required: true, message: "手机号为必填项", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value === "") {
            callback();
          } else if (!isPhone(value)) {
            callback(new Error("请输入正确的手机号码格式"));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ],
    ChannelCount: [
      { required: true, message: "频道数量为必填项", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          const num = Number(value);
          if (isNaN(num) || num < 3 || num > 20) {
            callback(new Error("频道数量必须在3-20之间"));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ],
    Code1: [
      { required: true, message: "用户关联码为必填项", trigger: "blur" },
      {
        validator: async (rule, value, callback) => {
          if (!value) {
            callback();
            return;
          }

          try {
            const params = {
              type: "user_loginbind",
              keyword: value
            };

            console.log("Code1唯一性检查参数", params);
            const res = await http.get(
              changeHttpLink("/api/Common/check-unique"),
              { params }
            );
            console.log("Code1唯一性检查结果", res);
            // 添加类型断言以解决TypeScript类型检查问题
            const typedRes = res as {
              Success: boolean;
              Data?: boolean;
            };
            if (typedRes.Success && typedRes.Data) {
              // 检查通过
              console.log("Code1检查通过");
              callback();
            } else {
              callback(new Error("用户关联码已存在"));
            }
          } catch (error) {
            console.error("Code1唯一性检查失败", error);
            callback(new Error("用户关联码唯一性检查失败，请稍后重试"));
          }
        },
        trigger: "blur"
      }
    ]
  });
}

// 保留原有的formRules以便向后兼容
// 在实际应用中，建议更新所有使用formRules的地方使用getFormRules函数
export const formRules = getFormRules();
